package org.lamb.framework.common.util;

import org.lamb.framework.common.remote.FacadeResult;
import org.lamb.framework.common.util.StringUtil;

import java.util.Objects;

/**
 * Li.D
 * dubbo服务的传递值时候的类型转换
 */
public class FacadeResultUtils {

    /**
     * 把json字符串转成FacadeResult的泛型对象
     * @param str
     * @param <T>
     * @return
     */
    public static <T> FacadeResult<T> stringToFacadeBean(String str, Class<T> clazz) {
        FacadeResult<String> facadeResult = StringUtil.stringToBean(str,FacadeResult.class);
        if (facadeResult.isSuccess()){
            String dataStr = facadeResult.getData();
            T t = StringUtil.stringToBean(dataStr,clazz);
            return FacadeResult.buildSucc(t);
        }else{
            return FacadeResult.buildFail(facadeResult.getErrorMsg());
        }

    }

    /**
     * 把Bean转成json字符串包装到FacadeResult里面
     * @param value
     * @param <T>
     * @return
     */
    public static <T> String succFacadeBeanToString(T value) {
        if (Objects.isNull(value)){
            return StringUtil.beanToString(FacadeResult.buildSucc());
        }
        String dataResult = StringUtil.beanToString(value);
        return StringUtil.beanToString(FacadeResult.buildSucc(dataResult));
    }

    public static <T> String succFacadeBeanToString() {
        return StringUtil.beanToString(FacadeResult.buildSucc());
    }

    public static <T> String failFacadeBeanToString(String errorMsg) {
        return StringUtil.beanToString(FacadeResult.buildFail(errorMsg));
    }
}
